package gossip.v2.cluster;

import lombok.Getter;

// 指数退避策略实现
@Getter
public class ExponentialBackoff {
    private final long initialDelay;
    private final long maxDelay;
    private long currentDelay;
    private final double backoffFactor;

    public ExponentialBackoff(long initialDelay, long maxDelay) {
        this(initialDelay, maxDelay, 2.0);
    }

    public ExponentialBackoff(long initialDelay, long maxDelay, double backoffFactor) {
        this.initialDelay = initialDelay;
        this.maxDelay = maxDelay;
        this.currentDelay = initialDelay;
        this.backoffFactor = backoffFactor;
    }

    public void waitAfterFailure() {
        try {
            Thread.sleep(currentDelay);
            currentDelay = Math.min((long) (currentDelay * backoffFactor), maxDelay);
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
        }
    }

    public void reset() {
        currentDelay = initialDelay;
    }
}
